package com.ias.agdis_r.activity.more;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckedTextView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ias.agdis_r.R;
import com.ias.agdis_r.activity.BaseActivity;
import com.ias.agdis_r.adapter.WorkGroupListAdapter;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.module.MessageModel;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponseHeader;
import com.ias.agdis_r.terminalmanager.restful.workgroup.request.WorkGroupAddMemberRequest;
import com.ias.agdis_r.terminalmanager.restful.workgroup.request.WorkGroupDeleteMembersRequest;
import com.ias.agdis_r.terminalmanager.restful.workgroup.response.WorkGroupAddMemberResponse;
import com.ias.agdis_r.terminalmanager.restful.workgroup.response.WorkGroupDeleteMembersResponse;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.Member;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.WorkGroupAddMemberRequestVO;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.WorkGroupAddMemberResponseVO;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.WorkGroupDeleteMembersRequestVO;
import com.ias.agdis_r.terminalmanager.restful.workgroup.vo.WorkGroupLoadMembersResponseVO;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.network.HttpUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * 班组列表页面
 */
public class WorkGroupActivity extends BaseActivity implements ListView.MultiChoiceModeListener{

    ListView listView;
    WorkGroupListAdapter listAdapter;
    private List<Member> members = new ArrayList<>();       // 总人员
    // 手工添加人员请求码
    public static final int REQUEST_CODE_ADD_MEMBER = 0x001;
    private AlertDialog nfcDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_group);
        initActionBar();
        initView();
        checkMemberData();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initActionBar() {
        ActionBar actionBar = getActionBar();
        if (actionBar == null) {
            return;
        }
        actionBar.setCustomView(getLayoutInflater().inflate(R.layout.actionbar_box, (ViewGroup) actionBar.getCustomView(), false));
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setDisplayShowCustomEnabled(true);
        ((TextView) findViewById(R.id.title)).setText(R.string.work_group);
        findViewById(R.id.actionbar_box_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        ImageView addMemberBtn = (ImageView) findViewById(R.id.iv_refresh);
        addMemberBtn.setImageResource(R.drawable.work_group_add_member);
        addMemberBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WorkGroupActivity.this, WorkGroupSearchActivity.class);
                startActivityForResult(intent, REQUEST_CODE_ADD_MEMBER);
            }
        });
    }

    private void initView() {
        listView = (ListView) findViewById(R.id.list_view);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        listView.setMultiChoiceModeListener(this);
        // Header
        View headerView = LayoutInflater.from(this).inflate(R.layout.layout_work_group_item, listView, false);
        headerView.setBackgroundResource(R.color.lightblue);
        ((CheckedTextView) headerView.findViewById(android.R.id.text1)).setCheckMarkDrawable(null);
        listView.addHeaderView(headerView, null, false);

        listAdapter = new WorkGroupListAdapter(this, members);
        listView.setAdapter(listAdapter);
    }

    private void initData() {
        // 班组信息
        WorkGroupLoadMembersResponseVO loadMembers = JavaBeanManager.getInstance().getWorkGroupLoadInfo();
        members.clear();
        if (loadMembers != null && loadMembers.getMembers() != null) {
            members.addAll(loadMembers.getMembers());
        }
        listAdapter.notifyDataSetChanged();
    }

    private void checkMemberData() {
        Member member = (Member) getIntent().getSerializableExtra(MessageModel.workGroup);
        if (null != member && S.isNotEmpty(member.getMember_usno()) && S.isNotEmpty(member.getMember_name())) {
            showBindMemberDialog(member);
        }
    }

    private void showBindMemberDialog(final Member member) {
        hideNfcDialog();
        String message = getString(R.string.work_group_user_add, member.getMember_name());
        nfcDialog = new AlertDialog.Builder(this)
                .setTitle(R.string.prompt)
                .setMessage(message)
                .setNegativeButton(R.string.canel, null)
                .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        addMember(member);
                    }
                }).create();
        nfcDialog.show();
    }

    private void hideNfcDialog() {
        if (null != nfcDialog && nfcDialog.isShowing()) {
            nfcDialog.dismiss();
        }
    }

    @Override
    protected void onPause() {
        hideNfcDialog();
        super.onPause();
    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        MenuInflater menuInflater = mode.getMenuInflater();
        menuInflater.inflate(R.menu.work_group_menu, menu);
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        initActionModeTitle(mode);
        initAdapterCheckMode(listAdapter, true);
        return true;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        if (item.getItemId() == R.id.menu_work_group) {
            // 获取选择数据
            List<Member> checkedMembers = listAdapter.getCheckedMembers(listView.getCheckedItemPositions(), listView.getHeaderViewsCount());
            // 删除处理
            removeMembers(checkedMembers);
            // 退出
            mode.finish();
        }
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        initAdapterCheckMode(listAdapter, false);
    }

    @Override
    public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
        initActionModeTitle(mode);
    }

    /**
     * 初始化ActionMode模式标题
     * @param mode ActionMode
     */
    private void initActionModeTitle(ActionMode mode) {
        int checkedItemCount = listView.getCheckedItemCount();
        int totalCount = listView.getAdapter().getCount() - listView.getHeaderViewsCount();
        String title = getString(R.string.work_group_select_user_title) + "(" + checkedItemCount + "/" + totalCount + ")";
        mode.setTitle(title);
    }

    /**
     * 设置ListView Adapter是否进入选择模式
     * @param listAdapter
     * @param isCheck
     */
    private void initAdapterCheckMode(WorkGroupListAdapter listAdapter, boolean isCheck) {
        listAdapter.setCheckMode(isCheck);
        listAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_ADD_MEMBER:       // 添加人员返回
                if (data == null || !data.hasExtra("member")) {
                    return;
                }
                Member member = (Member) data.getSerializableExtra("member");
                // 添加人员处理
                addMember(member);
                break;
        }
    }

    /**
     * 班组添加人员
     * @param member 人员实体(需要有工号和姓名)
     */
    private void addMember(Member member) {
        if (member == null || S.isEmpty(member.getMember_usno())) {
            return;
        }
		UserInfoBean userInfo = JavaBeanManager.getInstance().getUserinfo();
        if (userInfo != null && userInfo.getEnb().equals(member.getMember_usno())) {
            EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_UPTO, getString(R.string.work_group_user_exist), false);
            return;
        }
        for (Member mem : members) {
            if (member.getMember_usno().equals(mem.getMember_usno())) {
                EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_BASE, DataBaseManager.getInstance().getContext().getString(R.string.work_group_user_exist), false);
                return;
            }
        }
        member.setCartdtime(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", Locale.getDefault()).format(new Date()));
        WorkGroupAddMemberRequestVO addMemberRequestVO = new WorkGroupAddMemberRequestVO();
        addMemberRequestVO.setMember(member);       // 默认force=true

        WorkGroupAddMemberRequest addMemberRequest = new WorkGroupAddMemberRequest();
        addMemberRequest.setWorkGroupAddMemberRequestVO(addMemberRequestVO);

        HttpUtil.getInstance().sendRequest(addMemberRequest, MessageModel.WGAM, true);
    }

    /**
     * 班组删除人员
     * @param members 人员列表
     */
    private void removeMembers(List<Member> members) {
        if (members == null || members.isEmpty()) {
            return;
        }
        WorkGroupDeleteMembersRequestVO deleteMembersRequestVO = new WorkGroupDeleteMembersRequestVO();
        deleteMembersRequestVO.setClean(false);
        deleteMembersRequestVO.setMembers(members);

        WorkGroupDeleteMembersRequest deleteMembersRequest = new WorkGroupDeleteMembersRequest();
        deleteMembersRequest.setWorkGroupDeleteMembersRequestVO(deleteMembersRequestVO);

        HttpUtil.getInstance().sendRequest(deleteMembersRequest, MessageModel.WGDM, true);
    }

    @Override
    protected void operateResponseSucess(String serviceId, BaseResponse response) {
        switch (serviceId) {
            case MessageModel.WGAM:     // 班组添加人员返回
                WorkGroupAddMemberResponse addMemberResponse = (WorkGroupAddMemberResponse) response;
                WorkGroupAddMemberResponseVO addMemberResponseVO = addMemberResponse.getWorkGroupAddMemberResponseVO();

                boolean isSuccess = "1".equals(addMemberResponseVO.getStatus());
                String message = getString(isSuccess ? R.string.work_group_add_member_success : R.string.work_group_add_member_failure);
                Toast.makeText(this, message, Toast.LENGTH_SHORT).show();

                if (isSuccess) {
                    Member member = addMemberResponseVO.getMember();
                    listAdapter.addMember(member);
                }
                break;
            case MessageModel.WGDM:     // 班组删除人员返回
                WorkGroupDeleteMembersResponse deleteMembersResponse = (WorkGroupDeleteMembersResponse) response;

                boolean removeSuccess = deleteMembersResponse.getHeader().getStatus() == BaseResponseHeader.STATUS_SUCCESS;
                String removeMessage = getString(removeSuccess ? R.string.work_group_remove_member_success : R.string.work_group_remove_member_failure);
                Toast.makeText(this, removeMessage, Toast.LENGTH_SHORT).show();

                if (removeSuccess) {
                    List<Member> members = deleteMembersResponse.getMembers();
                    listAdapter.removeMembers(members);     // 移除操作人员
                }
                break;
        }
    }

    @Override
    protected void updateUI(String tag) {
        if (MessageModel.CDOF.equals(tag)) {        // 班组成员被移出
            // 此方法能退出ActionMode模式，并重置ListView多选模式
            listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
            initData();
        }
    }

}
